<?php
	/**
	 * Created by PhpStorm.
	 * User: mybook-lhp
	 * Date: 18/4/16
	 * Time: 上午10:59
	 */

	namespace app\common\traits;


	use EasyWeChat\Factory;

	trait wechat
	{

		public function _initialize()
		{
			parent::_initialize();
		}


		static public function commit()
		{
			$type = config('wechat.type');
			return config("wechat.{$type}");
		}

		/**
		 * 公众号实例
		 * @return \EasyWeChat\OfficialAccount\Application
		 */
		static public function officialAccount()
		{
			return Factory::officialAccount(self::commit());
		}

		/**
		 * 小程序实例
		 * @return \EasyWeChat\MiniProgram\Application
		 */
		static public function miniProgram()
		{
			$config = [
				'app_id'        => 'wx3cf0f39249eb0exx',
				'secret'        => 'f1c242f4f28f735d4687abb469072axx',

				// 下面为可选项
				// 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
				'response_type' => 'array',

				'log' => [
					'level' => 'debug',
					'file'  => __DIR__ . '/wechat.log',
				],
			];

			return Factory::miniProgram($config);
		}

		/**
		 * 根据 jsCode 获取用户 session 信息
		 * @param $jsCode
		 * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
		 * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
		 */
		static public function getWxUserSession($jsCode)
		{
			return static::miniProgram()->auth->session($jsCode);
		}

		/**
		 * 微信小程序消息解密
		 * @param $session
		 * @param $iv
		 * @param $encryptData
		 * @return array
		 * @throws \EasyWeChat\Kernel\Exceptions\DecryptException
		 */
		static public function DeCode($session, $iv, $encryptData)
		{
			return static::miniProgram()->encryptor->decryptData($session, $iv, $encryptData);
		}


		/**
		 * 开放平台 实例
		 * @return \EasyWeChat\OpenPlatform\Application
		 */
		static public function openPlatform()
		{
			return Factory::openPlatform([]);
		}


		/**
		 * 企业微信
		 * @return mixed
		 */
		static public function Work()
		{
			return Factory::work([]);
		}

		/**
		 * 微信支付实例
		 * @return \EasyWeChat\Payment\Application
		 */
		static public function Pay()
		{
			return Factory::payment(self::commit());
		}

		/**
		 * 获取模板信息ID
		 * @param $tpl
		 * @return bool
		 */
		static public function getTplMsg($tpl)
		{
			$tpls = config('wechat.tplmsg');
			if (isset($tpls[$tpl]))
			{
				return $tpls[$tpl];
			}

			return false;
		}
	}